<template>
  <div @keyup.enter="reGetData()">
    <el-form class="query-table-form" :inline="true">
      <el-form-item>
        <el-input v-model="params.customer_name" placeholder="项目名称查询" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="params.corp_name" placeholder="负责人查询" :clearable="true"></el-input>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          clearable
          placeholder="地址查询"
          :auto-top="true"
          @change="reGetData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="reGetData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel('项目立项（未立项）')"
        >
          导出
        </el-button>
      </el-form-item>
    </el-form>

    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:address="scope">
        <div class="text-truncate" :title="scope.row.address">{{ scope.row.address }}</div>
      </template>
      <template v-slot:status="scope">
        <div class="badge" :class="`badge-${scope.row.itemStatusStyle}`">
          {{ scope.row.itemStatusLabel }}
        </div>
      </template>
      <template v-slot:tags="scope">
        <el-popover placement="top-start" title="附件状态" trigger="hover">
          <div v-for="(tag, index) in scope.row.tags" :key="index">
            <div>
              <i class="fa fa-fw mr-1" :class="tag.icon"></i>
              <span>{{ tag.tag }}</span>
            </div>
          </div>
          <span slot="reference" class="badge" :class="`badge-${scope.row.tagStyle}`">
            {{ scope.row.tagLabel }}
          </span>
        </el-popover>
      </template>
      <template v-slot:name="scope">
        <el-popover placement="top-start" title="项目经理" trigger="hover">
          <div>
            <div>{{ `A角： ${scope.row.res_a_name || '-'}；` }}</div>
            <div class="mb-2">{{ `电话： ${scope.row.res_a_phone || '-'}` }}</div>
            <div>{{ `B角： ${scope.row.res_b_name || '-'}；` }}</div>
            <div>{{ `电话： ${scope.row.res_b_phone || '-'}` }}</div>
          </div>
          <div slot="reference">
            <div class="status-label badge-info text-left w-100">
              <div>A角:{{ scope.row.res_a_name }}</div>
              <div>B角:{{ scope.row.res_b_name }}</div>
            </div>
          </div>
        </el-popover>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="reGetData"
      ></el-pagination>
    </div>

    <approve-edit-dialog
      :visible.sync="approveVisible"
      :query-id="relatedId"
      @success="reGetData"
      @attach-success="reGetData"
    ></approve-edit-dialog>

    <attach-dialog
      :visible.sync="attachVisible"
      :related-id="attachId"
      @success="reGetData"
    ></attach-dialog>

    <view-dialog :visible.sync="viewVisible" :related-data="viewRow"></view-dialog>
  </div>
</template>

<script>
import { enumGuatype, enumItemStatus } from '@/credit/plugins/enumTown'
import {
  enumPersonalTags,
  enumCompanyTags,
  applicationSlot,
} from '@/credit/views/city/self/normal/item/attach'
import baseMixins from '@/credit/views/city/self/normal/todoMixins'

import SelectAddress from '@/components/select/SelectAddress'
import ApproveEditDialog from '@/credit/views/county/unionProvince/components/ApproveEditDialog'
import AttachDialog from '@/credit/views/city/self/normal/item/AttachDialog'
import ViewDialog from '@/credit/views/city/self/normal/item/ViewDialog'

const enumAttachmetStatus = {
  0: '未完成',
  1: '已完成',
}

export const baseTableColumns = [
  {
    attrs: { label: '项目名称', prop: 'customer_name', minWidth: '110px' },
    process: (v, row) => ({
      attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
    }),
  },
  { attrs: { label: '业务类型', prop: 'guaType', align: 'center' } },
  { attrs: { label: '地址', prop: 'address' }, slot: 'address' },
  { attrs: { label: '负责人', prop: 'corp_name', align: 'center' } },
  { attrs: { label: '联系电话', prop: 'mobile_no', align: 'center' } },
]

export default {
  components: {
    SelectAddress,
    ApproveEditDialog,
    AttachDialog,
    ViewDialog,
  },
  mixins: [baseMixins],
  data() {
    return {
      order: {
        approved_date: 'desc',
      },
      params: {
        index: 1,
        size: 15,
        address_code: '',
        customer_name: '',
        corp_name: '',
        'task_type.eq': 4,
      },

      tableData: [],
      tableColumns: [
        ...baseTableColumns,
        { attrs: { label: '申请金额(万元)', prop: 'apply_funds', align: 'center' } },
        { attrs: { label: '推荐时间', prop: 'operateTime', width: 140 } },
        { attrs: { label: '项目来源', prop: 'submit_person_name', align: 'center' } },
        { attrs: { label: '项目经理', prop: 'resName', width: 100 }, slot: 'name' },
        { attrs: { label: '立项状态', align: 'center' }, slot: 'status' },
        { attrs: { label: '附件状态', align: 'center' }, slot: 'tags' },
        {
          attrs: { label: '操作', align: 'center', width: 170 },
          operations: [
            {
              content: '立项',
              icon: 'fa fa-gavel',
              event: this.handleEdit,
              ifRender: row => row.editable,
            },
            {
              content: '上传附件',
              icon: 'fa fa-clipboard',
              event: this.hanleAttach,
              ifRender: row => row.editable,
            },
            { content: '查看', icon: 'fa fa-search', event: this.handleEditReport },
          ],
        },
      ],

      approveVisible: false,
      relatedId: '',

      viewVisible: false,
      viewRow: {},

      attachVisible: false,
      attachId: '',
    }
  },
  computed: {
    // 复写mixins
    userParams() {
      return {
        'task_person.like': this.userId,
      }
    },
  },
  watch: {},
  mounted() {},
  created() {
    this.reGetData()
  },
  methods: {
    hanleAttach(row) {
      this.attachVisible = true
      this.attachId = row.customer_related_id
    },
    async reGetData() {
      this.getData().then(() => this.getAttach())
      this.$store.dispatch('getTaskCountBusSelf')
    },
    getAttach() {
      const relatedIds = this.tableData.map(item => item.customer_related_id).join(',')
      if (!relatedIds) return
      Promise.all([
        this.$api.getData({
          table: 'customer_apply_sign',
          params: {
            'sign_type.eq': 1,
            'customer_related_id.in': relatedIds,
          },
        }),
        this.$api.getData({
          table: 'datum_customer_attachment',
          params: {
            'customer_related_id.in': relatedIds,
          },
        }),
      ])
        .then(([signRes, attachRes]) => {
          const contracts = signRes.data || []
          const signObj = {}
          for (const contract of contracts) {
            const relatedId = contract.customer_related_id
            signObj[relatedId] = contract
          }

          const attachs = attachRes.data || []
          const attachObj = {}
          for (const attach of attachs) {
            const relatedId = attach.customer_related_id
            if (!attachObj[relatedId]) {
              attachObj[relatedId] = []
            }
            attachObj[relatedId].push(attach)
          }

          this.tableData = this.tableData.map(it => {
            const isCompany = +it.customer_type === 1
            const relatedId = it.customer_related_id
            const tags = isCompany ? enumCompanyTags : enumPersonalTags
            const atts = attachObj[relatedId] || []
            const sign = signObj[relatedId] || {}
            let hasFinish = true
            it.tags = tags.map(({ tag, required, slot }) => {
              const hasUpload =
                slot === applicationSlot && +(it.is_online_sign || 2) === 1
                  ? +(sign.sign_status || 0) >= 2
                  : atts.some(att => att.attachment_type === tag)
              if (hasFinish && required && !hasUpload) {
                hasFinish = false
              }
              return {
                tag,
                required,
                hasUpload,
                icon: hasUpload
                  ? 'text-success fa-check'
                  : required
                  ? 'text-danger fa-times'
                  : 'fa-minus',
              }
            })
            it.tagStyle = hasFinish ? 'success' : 'danger'
            it.tagLabel = hasFinish ? '已完成' : '未完成'
            return it
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleEdit(row) {
      this.approveVisible = true
      this.relatedId = row.customer_related_id || ''
    },
    handleEditReport(row) {
      this.viewRow = row
      this.viewVisible = true
    },
    dataAdapter(item) {
      item.guaType = enumGuatype[item.gua_type] || '-'
      item.resName = `A角: ${item.res_a_name} B角: ${item.res_b_name}`
      item.submitType = +item.submit_type
      const operateTime = item.submitType === 1 ? item.approved_date : item.create_time
      item.operateTime = this.$utils.dateFormat(operateTime, this.dateFmt)

      const itemStatus = enumItemStatus[item.item_status] || {}
      item.itemStatusLabel = itemStatus.label
      item.itemStatusStyle = itemStatus.css

      item.item_status = +item.item_status
      item.hasItem = item.item_status === 1
      item.editable = true // [item.res_a, item.res_b].includes(this.userId) && item.item_status === 0

      item.itemStatus = enumAttachmetStatus[item.datum_status]

      return item
    },
    handleCreditClose() {
      this.viewVisible = false
      if (this.viewMode) {
        return
      }
      this.getData(this.params.index)
    },
  },
}
</script>
<style lang="scss" scoped>
.status-label {
  display: inline-block;
  padding: 0.25em 0.4em;
  font-size: 75%;
  font-weight: 700;
  line-height: 1;
  text-align: center;
  vertical-align: baseline;
  border-radius: 0.25rem;
  transition: color 0.15s;
}
</style>
